package com.bear.richtext.type

import android.content.Context
import android.widget.FrameLayout
import androidx.core.view.setMargins
import com.bear.richtext.Constant
import com.bear.richtext.view.GifView
import com.bear.richtext.utils.Tools
import org.json.JSONObject

/**
 * gif图片组件
 */
class ItemGif() : RichItem() {

    companion object {
        const val GIF_PATH = "gifPath" //gif图片链接
    }

    private var gifPath: String? = null

    override fun toJson(): JSONObject {
        this.richView?.let {
            var jsonObject = JSONObject()
            jsonObject.put(TYPE, RichItemType.Gif)
            var attrs = JSONObject()
            attrs.put(GIF_PATH, gifPath)
            jsonObject.put(ATTRS, attrs)
            return jsonObject
        }
        return JSONObject()
    }

    override fun parse(context: Context, jsonObject: JSONObject): GifView {
        gifPath = jsonObject.optJSONObject(ATTRS).optString(GIF_PATH)
        val gifView = GifView(context)
        val layoutParams = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT
        )
        layoutParams.setMargins(Constant.Default_MARGIN)
        gifView.layoutParams = layoutParams
        gifPath?.let {
            Tools.getImgLoad().loadImg(context,it,gifView)
        }
        return gifView
    }

    constructor(context: Context, jsonObject: JSONObject) : this() {
        this.richView = parse(context, jsonObject)
    }

    override fun type(): RichItemType {
        return RichItemType.Gif
    }

}